package com.lvyq.myplayer.util

import android.os.Handler
import android.os.Looper
import android.util.Log
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException

/**
 * 文件描述：NetworkUtils
 * 作者：lvyq
 * 创建时间：2025-04-29
 * 修改时间：2025-04-29
 */
object NetworkUtils {
    private val client: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .addInterceptor { chain ->
                val request = chain.request().newBuilder()
                    //.addHeader("Authorization", "Bearer $token")  请求头
                    .build()
                chain.proceed(request)
            }
            .build()
    }
    private val gson: Gson by lazy { Gson() }

    /**
     * 执行 GET 请求并解析 JSON
     * @param url 完整请求地址
     * @param responseClass 响应数据对应的 Class 对象
     * @param successCallback 成功回调（主线程）
     * @param errorCallback 失败回调（主线程）
     */
    fun <T> get(
        url: String,
        responseClass: Class<T>,
        successCallback: (T) -> Unit,
        errorCallback: (String) -> Unit = {}
    ) {
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                if (!response.isSuccessful) {
                    val errorMsg = "请求失败，状态码：${response.code}"
                    Log.e("NetworkUtils", errorMsg)
                    Handler(Looper.getMainLooper()).post { errorCallback(errorMsg) }
                    return
                }

                val responseBody = response.body?.string() ?: run {
                    val errorMsg = "响应体为空"
                    Log.e("NetworkUtils", errorMsg)
                    Handler(Looper.getMainLooper()).post { errorCallback(errorMsg) }
                    return
                }

                try {
                    val result = gson.fromJson(responseBody, responseClass)
                    Handler(Looper.getMainLooper()).post { successCallback(result) }
                } catch (e: Exception) {
                    val errorMsg = "JSON 解析失败：${e.message}"
                    Log.e("NetworkUtils", errorMsg, e)
                    Handler(Looper.getMainLooper()).post { errorCallback(errorMsg) }
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                val errorMsg = "网络请求失败：${e.message}"
                Log.e("NetworkUtils", errorMsg, e)
                Handler(Looper.getMainLooper()).post { errorCallback(errorMsg) }
            }
        })
    }
}